<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $age = isset($_POST['age']) ? (int)$_POST['age'] : 0;
    $gender = isset($_POST['gender']) ? $_POST['gender'] : '';
    
    // 验证必填字段
    if (!$id || !$name || !$phone || !$email || !$age || !$gender) {
        echo json_encode(['status' => 'error', 'message' => '请填写完整信息']);
        exit;
    }
    
    // 验证手机号格式
    if (!preg_match("/^1[3-9]\d{9}$/", $phone)) {
        echo json_encode(['status' => 'error', 'message' => '手机号格式不正确']);
        exit;
    }
    
    // 验证邮箱格式
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => 'error', 'message' => '邮箱格式不正确']);
        exit;
    }
    
    // 验证年龄范围
    if ($age < 1 || $age > 120) {
        echo json_encode(['status' => 'error', 'message' => '年龄不合法']);
        exit;
    }
    
    // 验证性别
    if (!in_array($gender, ['1', '2'])) {
        echo json_encode(['status' => 'error', 'message' => '性别不合法']);
        exit;
    }
    
    // 检查手机号是否被其他用户使用
    $sql = "SELECT id FROM users WHERE phone = ? AND id != ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $phone, $id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => '手机号已被使用']);
        exit;
    }
    
    // 检查邮箱是否被其他用户使用
    $sql = "SELECT id FROM users WHERE email = ? AND id != ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $email, $id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => '邮箱已被使用']);
        exit;
    }
    
    // 更新用户信息
    $sql = "UPDATE users SET name = ?, phone = ?, email = ?, age = ?, gender = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssisi", $name, $phone, $email, $age, $gender, $id);
    
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => '更新失败']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '不支持的请求方法']);
}

$conn->close();
?> 